package com.atguigu.gmall.order.listener.mq;

import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.constant.MqConst;
import com.atguigu.gmall.mq.service.RabbitMqService;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.atguigu.gmall.order.vo.OrderPayedMsgVo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author lfy
 * @Description
 * @create 2023-08-05 15:12
 */
@Component
public class OrderPayedListener {

    @Autowired
    RabbitMqService mqService;

    @Autowired
    OrderBizService orderBizService;

    @RabbitListener(queues = MqConst.QUEUE_ORDER_PAYED)
    public void payed(Message message, Channel channel) throws IOException {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String json = new String(message.getBody());

        try {
            OrderPayedMsgVo msgVo = JSONs.jsonStr2Obj(json, OrderPayedMsgVo.class);
            String outTradeNo = msgVo.getOutTradeNo();
            //订单状态修改。有可能会产生临界支付。
            // 状态修改：未支付或者已关闭都可以改为已支付。
            // UNPAID = PAID，
            // CLOSED = PAID;
            // update order_info set order_status=paid and process_status=paid
            // where outTradeNo=? and user_id=? and order_status in (unpaid,closed)
            orderBizService.orderPayedStatusChange(msgVo.getOutTradeNo());


            //通知库存。

            channel.basicAck(deliveryTag,false);

        }catch (Exception e){
            mqService.retry(json,deliveryTag,channel,5);
        }

    }
}
